package com.server.llh.llhserverwork.activity.server;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;

import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseNFCActivity;
import com.server.llh.llhserverwork.adapter.LlhAddressItemAdapter;
import com.server.llh.llhserverwork.adapter.MyAccountAdapter;

import com.server.llh.llhserverwork.adapter.OptionSerOrderHolder;
import com.server.llh.llhserverwork.adapter.base.ListViewDataAdapter;
import com.server.llh.llhserverwork.bean.Account;
import com.server.llh.llhserverwork.bean.AccountConstant;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.MyAddress;

import com.server.llh.llhserverwork.bean.OptionOrderData;
import com.server.llh.llhserverwork.bean.PayList;
import com.server.llh.llhserverwork.bean.UserDataInfoBean;
import com.server.llh.llhserverwork.port.ClearViewDataInterface;
import com.server.llh.llhserverwork.receiver.GetCardBroadCast;
import com.server.llh.llhserverwork.utils.Constant;
import com.server.llh.llhserverwork.utils.ListViewHeightUtil;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.ServerStatementData;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.utils.ToastTool;
import com.server.llh.llhserverwork.view.AddListView;
import com.server.llh.llhserverwork.view.AlertDialog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 服务下单页面
 */
public class LlhOptionSubOrderActivity extends LlhBaseNFCActivity {

    private static final String TAG = "ShopingOrder";
    @BindView(R.id.order_code)
    TextView orderCode;
    @BindView(R.id.amountPayable)
    TextView amountPayable;
    @BindView(R.id.payStatus)
    TextView payStatus;
    @BindView(R.id.left_btn)
    ImageButton leftBtn;
    @BindView(R.id.titlebar_text)
    TextView titlebarText;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.addAddress)
    LinearLayout addAddressLayout;
    @BindView(R.id.addressTxt)
    TextView addressTxt;
    @BindView(R.id.userNameTxt)
    TextView userNameTxt;
    @BindView(R.id.userPhoneTxt)
    TextView userPhoneTxt;
    @BindView(R.id.image_break)
    ImageView imageBreak;
    @BindView(R.id.address_content)
    RelativeLayout addressContent;
    @BindView(R.id.show_address_all)
    LinearLayout showAddressAll;
    @BindView(R.id.address_lv)
    AddListView addressLv;
    @BindView(R.id.layout_show)
    ImageView layoutShow;
    @BindView(R.id.view_pay)
    RelativeLayout viewPay;
    @BindView(R.id.radio0)
    ImageView radio0;
    @BindView(R.id.relative1)
    RelativeLayout relative1;
    @BindView(R.id.radio1)
    ImageView radio1;
    @BindView(R.id.relative2)
    RelativeLayout relative2;
    @BindView(R.id.LinearLayout1)
    LinearLayout LinearLayout1;
    @BindView(R.id.order_list)
    AddListView orderList;
    @BindView(R.id.order_content)
    LinearLayout orderContent;
    @BindView(R.id.sv_order_content)
    ScrollView svOrderContent;
    @BindView(R.id.text_money)
    TextView textMoney;
    @BindView(R.id.text_money_count)
    TextView textMoneyCount;
    @BindView(R.id.btn_commint)
    Button btnCommint;
    @BindView(R.id.show_address)
    RelativeLayout showAddress;

    @BindView(R.id.my_user_name)
    TextView myUserName;
    @BindView(R.id.user_old_man_sp)
    TextView userOldManSp;
    @BindView(R.id.pay_list)
    Spinner pay_list;
    @BindView(R.id.view_line)
    LinearLayout viewLine;
    @BindView(R.id.add_address)
    LinearLayout addAddress;
    @BindView(R.id.address)
    LinearLayout address;
    @BindView(R.id.zhifu_Style)
    TextView zhifuStyle;
    @BindView(R.id.zhifu_card)
    TextView zhifuCard;

    private List<MyAddress> objects = new ArrayList<MyAddress>();
    ServerStatementData serverStatementData;
    private String mUserId1, mUserId, accId, packId, mOrgId, mOrgName, mOrgType, mUserName1, mUserName, mToken, mPhone, amountPayableD;
    List<ServerStatementData.SerOrderInfoDetailBeanListBean> listBeen = new ArrayList<>();
    double myBanlance;
    GetCardBroadCast getCardBroadCast = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.READ_CARDACTION);
        getCardBroadCast = new GetCardBroadCast();
        getCardBroadCast.setmHandler(handler);
        getLbm().registerReceiver(getCardBroadCast, filter);
        addAddress.setVisibility(View.GONE);
        btnCommint.setText("购买服务");
        mUserId1 = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_ID, getApplicationContext());
        mPhone = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TELE_PHONE, getApplicationContext());
        mOrgId = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_ID, getApplicationContext());
        Log.d(TAG, "dataBean.getAdminOrgId()2==" + mOrgId);
        mOrgName = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_NAME, getApplicationContext());
        mOrgType = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.ORG_TYPE, getApplicationContext());
        mUserName = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.USER_NAMW, getApplicationContext());
        mToken = SharedPreferenceUtil.getUserInfo(Constants.UserInfo.TOKEN_STR, getApplicationContext());
        serverStatementData = LlhServerOptionActivity.serverStatementData;
        if (serverStatementData != null) {
            orderCode.setVisibility(View.GONE);
//            orderCode.setText("订单号:" + serverStatementData.getSerOrderInfo().getOrderCode());
            amountPayable.setText("总价:￥" + serverStatementData.getSerOrderInfo().getAmountPayable() + "元");
            amountPayableD = serverStatementData.getSerOrderInfo().getAmountPayable() + "";
            textMoney.setText("总价:￥" + serverStatementData.getSerOrderInfo().getAmountPayable() + "元");
            packId = serverStatementData.getSerOrderInfoDetailBeanList().get(0).getSerOrderInfoDetail().getPackageId() + "";
            if (serverStatementData.getSerOrderInfo().getPayStatus() == 0) {
                payStatus.setText("未支付");
            }
        }
        try {
            if (serverStatementData.getSerOrderInfoDetailBeanList() != null) {
                listBeen = serverStatementData.getSerOrderInfoDetailBeanList();
                if (listBeen != null) {
                    ListViewDataAdapter<ServerStatementData.SerOrderInfoDetailBeanListBean> adapter = new ListViewDataAdapter<ServerStatementData.SerOrderInfoDetailBeanListBean>(null);
                    adapter.update(listBeen);
                    adapter.setViewHolderClass(null, OptionSerOrderHolder.class, this);
                    orderList.setAdapter(adapter);
                    ListViewHeightUtil.setListViewHeightBasedOnChildren(orderList);
                }
            }
        } catch (Exception e) {
        }
        pay_list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                payTypeInt = accountList.get(position).getAcctype();
                Log.d(TAG, "payTypeInt===" + payTypeInt);
                accId = accountList.get(position).getAccid();
                myBanlance = accountList.get(position).getBalance();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    View view;
    private int payTypeInt;
    @OnClick({R.id.addAddress, R.id.image_break, R.id.left_btn, R.id.right_btn, R.id.address_content, R.id.show_address_all, R.id.layout_show, R.id.view_pay, R.id.radio0, R.id.relative1, R.id.relative2, R.id.LinearLayout1, R.id.order_content, R.id.btn_commint, R.id.show_address})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_btn:
                onBackPressed();
                break;

            case R.id.btn_commint:

                if (serverStatementData == null) {
                    T.showAnimToast(getApplicationContext(), "数据为空");
                    return;
                }
                if (accId == null) {
                    T.showAnimToast(getApplicationContext(), "请刷卡获取用户信息！");
                    return;
                }
                if (serverStatementData.getSerOrderInfo() != null) {
                    if (myBanlance >= serverStatementData.getSerOrderInfo().getAmountPayable()) {
                        reqOrderPatment(accId, payTypeInt, amountPayableD, mOrgId, packId);
                    } else {
                        T.showAnimToast(getApplicationContext(), "余额不足，请选择其他账户，进行支付！");
                    }
                }
                break;
            case R.id.show_address:
                break;
            case R.id.image_break:
                setShowAddress();
                break;
        }
    }
    private void setShowAddress() {
        if (objects != null && addressLv.getVisibility() == View.GONE) {
            imageBreak.setVisibility(View.VISIBLE);
            addressLv.setVisibility(View.VISIBLE);
        } else if (addressLv.getVisibility() == View.VISIBLE) {
            addressLv.setVisibility(View.GONE);
        }
    }
    String cardId;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == -1000) {
                cardId = String.valueOf(msg.obj);
                Log.d(TAG, "cardId==" + cardId);
                getUserInfo(String.valueOf(cardId));
            }
        }
    };
    Account account = null;
    MyAccountAdapter accountAdapters = null;
    List<Account.DataBean> accountList = new ArrayList<Account.DataBean>();
    public void accoutByRelated(String userId) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", mToken);
        lRequest.addParam("userId", userId);
        lRequest.addParam("accTypes", "1,6,7,10");
        lRequest.setUri(ServerPort.ACC_BY_RELATED);
        lRequest.setUriType(UrlsTools.ACCOUNT_INFO);
        lRequest.setIp(UrlsTools.REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "请求超时！");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null && "0".equals(code)) {
                    Log.d(TAG, "responseBean222==" + responseBean);
                    account = new Gson().fromJson(responseBean, Account.class);
                    if (account != null) {
                        if (account.getData() != null && account.getData().size() > 0) {
                            accountList = account.getData();
                            accountAdapters = new MyAccountAdapter(getApplicationContext(), accountList);
                            pay_list.setAdapter(accountAdapters);
//                            pay_list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//                            Handler handler = new Handler();
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//
//                                    pay_list.setSelected(true);
//                                    pay_list.setSelection(0);
//                                    pay_list.setItemChecked(0, true);
//                                    pay_list.performItemClick(pay_list.getChildAt(0), 0, 0);
//                                }
//                            }, 500);
                        }
                    }
                } else {
                    T.showAnimToast(getApplicationContext(), "账户信息为空！");
                }
            }
        });
    }
    /**
     * 下单支付
     * @param amount
     */
    private void reqOrderPatment(String accId, int getAcctype, String amount, String mOrgId, String packId) {
        try {
            if (packId == null && TextUtils.isEmpty(packId)) {
                T.showAnimToast(getApplicationContext(), "当前数据为空！");
                return;
            }
            PayList payList = new PayList();
            if (getAcctype == 1) {
                payList.add(accId, AccountConstant.PayType.CASH_ACCOUNT, Double.valueOf(amount), mOrgId);
            } else if (getAcctype == 6 || getAcctype == 7) {
                payList.add(accId, AccountConstant.PayType.ACTIVE_CARD, Double.valueOf(amount), mOrgId);
            } else if (getAcctype == 10) {
                payList.add(accId, AccountConstant.PayType.COUPON, Double.valueOf(amount), mOrgId);
            }
            payList.setConsumeType(AccountConstant.ConsumeType.CONSUME_SERVICE);
            payList.setOrderid(mOrgId);
            String payStr = new Gson().toJson(payList);
            Log.d(TAG, "payStr===" + payStr);
            LRequest lRequest = new LRequest();
            lRequest.addParam("orderData", URLEncoder.encode(setOptionOrderData(packId), "utf-8"));
            lRequest.addParam("token", mToken);
            lRequest.addParam("amountTotal", amountPayableD);
            lRequest.addParam("payList", URLEncoder.encode(payStr, "utf-8"));
            lRequest.setUri(ServerPort.CREATE_SERVER_ORDER_INFO);
            lRequest.setReqType(UrlsTools.SERVER_TASK_REQ);
            lRequest.setUriType(UrlsTools.SERVER_TASK_REQ);
            lRequest.setIp(UrlsTools.SERVER_REQ_URL);
            lRequest.setType(String.class);
            requestData(lRequest, new NetDataListener<String>() {
                @Override
                public void onError(Throwable t) {
                    T.showAnimErrorToast(getApplicationContext(), getResources().getString(R.string.toast_str));
                }

                @Override
                public void onNext(String responseBean, String code) {
                    if ("200".equals(code)) {

                        showInfo();
                    } else {

                        T.showAnimToast(getApplicationContext(), "余额不足，请选择其他账户，进行支付！");
                    }
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    static ClearViewDataInterface clearViewDataInterfaces = null;
    public static void registCallBack(ClearViewDataInterface clearViewDataInterface) {
        clearViewDataInterfaces = clearViewDataInterface;
    }
    private void showInfo() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("购买成功");
        builder.setMessage("\n" + "购买成功，祝你生活愉快！" + "\n");
        builder.setNegativeButton("确认退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                clearViewDataInterfaces.clearShopData("1");
                finish();
                dialog.cancel();
            }
        });
        builder.setPositiveButton("继续订购", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                clearViewDataInterfaces.clearShopData("0");
                finish();
                dialog.cancel();
            }
        });
        builder.show();
    }
    public void getUserInfo(String icNumber) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", mToken);
        lRequest.addParam("icNumber", icNumber);
        lRequest.setUri(ServerPort.GET_CARD_INFO);
        lRequest.setUriType("");
        lRequest.setIp(UrlsTools.REQ_URL);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "请求超时！");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null && "0".equals(code)) {
                    UserDataInfoBean userDataInfoBean = new Gson().fromJson(responseBean, UserDataInfoBean.class);
                    userOldManSp.setText(userDataInfoBean.getData().getUserName());
                    myUserName.setText("请选择");
//                    mOrgId = userDataInfoBean.getData().getUserOrgId();
                    mUserId = userDataInfoBean.getData().getUserId();
                    if (userDataInfoBean.getData().getUserNickName() != null) {
                        mUserName1 = userDataInfoBean.getData().getUserName() + "(" + userDataInfoBean.getData().getUserNickName() + ")";
                    } else {
                        mUserName1 = userDataInfoBean.getData().getUserName();
                    }
                    accoutByRelated(userDataInfoBean.getData().getUserId());
                } else {
                    ToastTool.showText(getApplicationContext(), "没有找到该卡所对应的用户信息！");
                }
            }
        });
    }
    public String setOptionOrderData(String packId) {
        OptionOrderData optionOrderData = new OptionOrderData();
        optionOrderData.setCustomerId(mUserId);
        optionOrderData.setOrderPersionId(mUserId1);
        optionOrderData.setOrderPersionName(mUserName);
        optionOrderData.setCustomerName(mUserName1);
        optionOrderData.setSupplierId(mOrgId);
        optionOrderData.setWaiterId(mUserId1);
        optionOrderData.setWaiterName(mUserName);
        optionOrderData.setSupplierName(mOrgName);
        optionOrderData.setSupplierTypeId(mOrgType);
        optionOrderData.setPackId(packId);
        optionOrderData.setAmountTotal(Double.valueOf(amountPayableD));
        String orderData = new Gson().toJson(optionOrderData);
        return orderData;
    }
    private void showInfo(final int payStatus) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        if (payStatus == 0) {
            builder.setTitle("订单支付成功！");
            builder.setMessage("\n" + "订单支付成功，祝你生活愉快！" + "\n");
        } else {
            builder.setTitle("订单支付失败！");
            builder.setMessage("\n" + "余额不足支付失败！" + "\n");
        }
        builder.setNegativeButton("查看订单", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (payStatus == 0) {
                    Intent intent = new Intent(getApplicationContext(), LlhServerOrderBaseFragment.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getApplicationContext(), LlhServerOrderBaseFragment.class);
                    intent.putExtra("userId", mUserId);
                    startActivity(intent);
                }
                dialog.cancel();
            }
        });
        builder.setPositiveButton("继续订购", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                dialog.cancel();
            }
        });
        builder.show();
    }
    protected int getlayout() {
        return R.layout.llh_shoping_order;
    }
    @Override
    protected void initView() {
    }
    @Override
    protected void doBasess() {

    }
    public void showProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    showProgress(LlhOptionSubOrderActivity.this);
                } catch (Exception e) {
                }
            }
        });
    }
    public void hideProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    closeProgress();
                } catch (Exception e) {
                }
            }
        });
    }
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }
    @Override
    protected void onDestroy() {
        try {
            if (getCardBroadCast != null) {
                unregisterReceiver(getCardBroadCast);
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        super.onDestroy();
    }
}